package com.skit.ecm

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.zxing.integration.android.IntentIntegrator
import com.skit.common.base.BaseActivity
import com.skit.common.manager.UserManager
import com.skit.ecm.adapter.HomeViewPagerAdapter
import com.skit.ecm.fragment.HomeFragment
import com.skit.ecm.search.SearchFragment
import com.skit.main.ui.add.AddActivity
import com.skit.main.fragment.HomeActivityFragment
import com.skit.mine.fragment.PersonFragment
import com.skit.schedule.fragment.ScheduleFragment
import com.skit.score.fragment.ScoreFragment
import com.skit.zixing.QRCodeScanActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.activity_main.*

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since 2020/4/23
 */

@Route(path = "/app/main")
@AndroidEntryPoint
class MainActivity : BaseActivity() {
    private lateinit var relativeLayout: RelativeLayout
    private val fragments: ArrayList<Fragment> = ArrayList()
    lateinit var viewPagerAdapter: HomeViewPagerAdapter
    lateinit var top_title: TextView
    lateinit var search_card: CardView

    private var lastIndex = 0

    companion object {
        private const val TAG = "MainActivity"
    }

    val titles = arrayOf("首页", "日程", "成绩", "我的")
    override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.Main)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        top_title = findViewById(R.id.top_title)
        relativeLayout = findViewById(R.id.relativeLayout)
        search_card = findViewById(R.id.search_card)


        search_card.setOnClickListener {
            val beginTransaction = supportFragmentManager.beginTransaction()
//            beginTransaction.add(SearchFragment.newInstance(), "搜索")
            beginTransaction.replace(R.id.fragmentContainer, SearchFragment.newInstance(), "搜索")
            beginTransaction.addToBackStack(null)
            beginTransaction.commit()
            replaceTopView()
        }

        fragments.apply {
//            add(HomeActivityFragment.newInstance().apply {
//                scrollGJ = {
//                    scrollTop(it)
//                }
//            })
            add(HomeFragment.newInstance().apply {
                scrollGJ = {
                    scrollTop(it)
                }
            })
            add(ScheduleFragment.newInstance().apply {
                scrollGJ = {
                    scrollTop(it)
                }
            })
            add(ScoreFragment.newInstance())
            add(PersonFragment.newInstance())
        }

        viewPagerAdapter = HomeViewPagerAdapter(fragments, this)
        viewPager2.apply {
            offscreenPageLimit = fragments.size
            adapter = viewPagerAdapter
            isUserInputEnabled = false
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    setTopTile(titles[currentItem])
                    bottomNavigationView.menu.getItem(position).isChecked = true
                }
            })
        }

        bottomNavigationView.setOnNavigationItemSelectedListener {
            val currentItem: Int = when (it.itemId) {
                R.id.nav_home -> 0
                R.id.nav_schedule -> 1
                R.id.nav_score -> 2
                R.id.nav_person -> 3
                else -> 0
            }
            viewPager2.setCurrentItem(currentItem, false)
            false
        }

    }

    fun setTopTile(text: String) {
        if ("我的" == text) {
            search_card.visibility = View.GONE
        } else {
            search_card.visibility =
                if (search_card.visibility == View.GONE) View.VISIBLE else search_card.visibility
        }
        replaceTopView()
        top_title.text = text
    }

    private fun replaceTopView() {
        lastIndex = 0
        appbar.apply {
            translationY = 0f
            appbar.requestLayout()
        }

        (viewPager2.layoutParams as ViewGroup.MarginLayoutParams).apply {
            topMargin = appbar.height
            viewPager2.requestLayout()
        }
    }

    override fun onResume() {
        super.onResume()
        UserManager.checkLogin()
    }


    private fun scrollTop(dy: Int) {
        if (dy > 0 && lastIndex == -relativeLayout.height) {
            Log.d(HomeActivityFragment.TAG, "scrollTop: ")
            return
        }
        appbar.apply {
            translationY = if (dy < 0 && lastIndex >= 0) {
                0F
            } else if (dy > 0 && lastIndex < 0 && -lastIndex >= relativeLayout.height) {
                -relativeLayout.height.toFloat()
            } else {
                (translationY + (-dy.toFloat() * 0.5f))
            }
            lastIndex = translationY.toInt()
            appbar.requestLayout()
        }
        (viewPager2.layoutParams as ViewGroup.MarginLayoutParams).apply {
            topMargin = if (lastIndex == 0) appbar.height else (appbar.height + lastIndex)
            viewPager2.requestLayout()
        }
    }

    fun scan(view: View) {
        IntentIntegrator(this).setCaptureActivity(QRCodeScanActivity::class.java)
            .initiateScan()
    }

    fun add(view: View) {
        startActivity(Intent(this, AddActivity::class.java))
    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    override fun event(eventMessage: EventMessage) {
//        when (eventMessage.code) {
//            EventMessage.MessageCode.LOGOUT -> {
//
//            }
//        }
//    }

}
